<%@ page language="java" contentType="text/html;charset=UTF-8"%>
<%@ include file="/WEB-INF/views/include/taglib.jsp"%>
<%@include file="/WEB-INF/views/include/head.jsp"%>
<html>
<head>
	<meta name="decorator" content="sysDefault"/>
	<title>公式定义</title>
	<link href="${staticPath}/lib/datetimepicker/0.0.11/css/bootstrap-datetimepicker.min.css" rel="stylesheet" type="text/css">
	<link href="${staticPath}/lib/chosen/1.1.0/chosen.min.css" rel="stylesheet" type="text/css">
	<link rel="stylesheet" href="${staticPath}/lib/ztree/3.5/css/zTreeStyle/zTreeStyle.css" type="text/css">
	<style type="text/css">
		ul,li{padding:0px; margin:0px; list-style:none;}
		.left{width:30%; background:#f7f7f7; float:left; height:420px;padding: 30px 10px;}
		.right{width:70%; background:#f7f7f7; float:left; overflow:hidden;}
		.right_1{background:#f7f7f7; height:260px;}
		.right_1 ul li{line-height:30px;}
		.right_2{background:#f7f7f7; height:120px;}
		.right_3{background:#f7f7f7; height:40px;}
		.bigButton{width:60px;}
	</style> 
	<!-- 选择对话框依赖的js -->
	<script src="${staticPath}/lib/ztree/3.5/js/jquery.ztree.all-3.5.js" type="text/javascript"></script>
	
	<script type="text/javascript">
	//定义全局变量
	var formulaGobalInfo = {};
	formulaGobalInfo.varInfo = {};
	formulaGobalInfo.basedataInfo = {};
	formulaGobalInfo.serviceInfo = {};
	//往公式中添加字符
	function opFormula(param, space){
		var area = $("#expression");
		if (space == null)
    		space = '';
		var selectValue = space + param + space;
		//IE support
        if (document.selection) 
        {
        	area.focus();
        	document.selection.createRange().text= space + param + space;
        }
        //MOZILLA/NETSCAPE support
        else if (area.selectionStart || area.selectionStart == '0') 
        {
            var startPos = area.selectionStart;
            var endPos = area.selectionEnd;
            // save scrollTop before insert
            var restoreTop    = area.scrollTop;
            area.val(area.val().substring(0, startPos) + space + param + space + area.val().substring(endPos, area.val().length));
            if (restoreTop > 0)
            {
                // restore previous scrollTop
                area.scrollTop = restoreTop;
            }
            area.focus();
            area.selectionStart    = startPos + area.val().length;
            area.selectionEnd    = startPos + area.val().length;
        } else {
            var area = document.getElementById("expression"); 
            var value = area.value;
	        var range = getSelection(area);
	        var start = value.substring(0, range.selectionStart);
	        var end = value.substring(range.selectionEnd, value.length);
	        var sl = area.scrollLeft,st = area.scrollTop;
	        area.value = start + selectValue + end;
	        area.scrollLeft = sl;
	        area.scrollTop = st;
	        var np = start.length + selectValue.length;
	        area.setSelectionRange(np, np);
        }
	}
	
	function getSelection(area) {
        area.focus();
        return {
            selectionStart:area.selectionStart,
            selectionEnd:area.selectionEnd
        };
    }
	
	function setSelectionRange(start, end) {
		var area = document.getElementById("expression"); 
        var v = area.value;
        var range = area.createRange();
        range.collapse(true);
        start = getLengthForRange(v, start);
        end = getLengthForRange(v, end);
        range.moveEnd("character", end);
        range.moveStart("character", start);
        //select 附带 focus 效果哦
        //内部应该是：
        //1.focus
        //2.select
        range.select();
        area.focus();
    }
	
	function getLengthForRange(text, v) {
        return text.substring(0, v).replace(/\r\n/g, "\n").length;
    }
	//清空数据
	function cleanInfo(){
		$("#expression").val("");
	}
	//替换中文字符
	function replaceSymbol(str){
		str = str.replace(/，/g, ",");
		str = str.replace(/。/g, ".");
		str = str.replace(/：/g, ":");
		str = str.replace(/；/g, ";");
		str = str.replace(/＋/g, "+");
		str = str.replace(/－/g, "-");
		str = str.replace(/×/g, "*");
		str = str.replace(/÷/g, "/");
		str = str.replace(/（/g, "(");
		str = str.replace(/）/g, ")");
		str = str.replace(/《/g, "<");
		str = str.replace(/》/g, ">");
		str = str.replace(/‘/g, "\'");
		str = str.replace(/’/g, "\'");
		str = str.replace(/“/g, "\"");
		str = str.replace(/”/g, "\"");
		return str;
	}
	//根据变量名取ID
	function getVarIdByName(varName, isFunc){
		if(isFunc){
			var funcInfo = formulaGobalInfo.serviceInfo;
			for(var key in funcInfo){  
				if(funcInfo[key] == varName){
					return key;
				}
		    }  
		}else{
			var varInfo = formulaGobalInfo.varInfo;
			for(var key in varInfo){  
				if(varInfo[key] == varName){
					return key;
				} 
		    }  
		}
	}
	//获取下个变量位置的信息
	function getNextInfo(script, preInfo,mark){
		var rtnVal = {};
		rtnVal.leftIndex = script.indexOf(mark, preInfo==null?0:preInfo.rightIndex+1);
		if(rtnVal.leftIndex==-1)
			return null;
		rtnVal.rightIndex = script.indexOf(mark, rtnVal.leftIndex+1);
		if(rtnVal.rightIndex==-1)
			return null;
		rtnVal.varName = script.substring(rtnVal.leftIndex + 1, rtnVal.rightIndex);
		rtnVal.isFunc = (mark == "#")?true:false; 
		return rtnVal;
	}
	//提交
	function submit(){
		//转换中文字符
		var expressionInfo = $("#expression").val();
		//转换表达式
		//转换表达式
		var scriptIn = replaceSymbol(expressionInfo);
		var preInfo = {rightIndex:-1};
		var scriptOut = "";
		//替换变量
		for (var nxtInfo = getNextInfo(scriptIn, preInfo,"$"); nxtInfo!=null; nxtInfo = getNextInfo(scriptIn, nxtInfo,"$")) {
			var varId = getVarIdByName(nxtInfo.varName, nxtInfo.isFunc);
			if(varId==null){
				alert((nxtInfo.isFunc ? message_unknowfunc : message_unknowvar) + nxtInfo.varName);
				return;
			}
			scriptOut += scriptIn.substring(preInfo.rightIndex+1, nxtInfo.leftIndex) + " " + varId + " ";
			preInfo = nxtInfo;
		}
		//替换方法
		for (var nxtInfo = getNextInfo(scriptIn, preInfo,"#"); nxtInfo!=null; nxtInfo = getNextInfo(scriptIn, nxtInfo,"#")) {
			var varId = getVarIdByName(nxtInfo.varName, nxtInfo.isFunc);
			if(varId==null){
				alert((nxtInfo.isFunc ? message_unknowfunc : message_unknowvar) + nxtInfo.varName);
				return;
			}
			scriptOut += scriptIn.substring(preInfo.rightIndex+1, nxtInfo.leftIndex) + " " + varId + " ";
			preInfo = nxtInfo;
		}
		scriptOut += scriptIn.substring(preInfo.rightIndex+1);
		//校验两个变量并列的错误
		if(scriptOut.indexOf("$$")>-1){
			alert(message_eval_error);
			return;
		}
		var result = new Object();
		result.idField = $.trim(scriptOut);
		result.nameField = $.trim(expressionInfo);
		window.returnValue=result;
		window.close();
	}
	//变量树
	//初始化变量树
	var setting_vars = {
		async: {
			enable: true,
			url:Com_Parameter.ContextPath + "/common/getDataList?s_bean=getVarDataService&proDefId="+window.dialogArguments.proDefId,
			dataFilter: ajaxDataFilterVar
		},
		view:{
			showLine: false,
			dblClickExpand: false
		},
		data : {
			simpleData : {
				enable : true
			},
			key :{
				title : "fullName",
				isFun : "isFun",
				isData : "isData"
			}
		},
		callback: {
			onMouseDown: zTreeOnMouseDown
		}
	};
	
	function ajaxDataFilterVar(treeId, parentNode, responseData) {
	   if (responseData) {
	      for(var i =0; i < responseData.length; i++) {
	    	  if(responseData[i].isData)
	    	  	formulaGobalInfo.varInfo[responseData[i].id] = responseData[i].name;
	      }
	   }
	   return responseData;
	};
	
	//初始化数据字典树
	var setting_basedata = {
		async: {
			enable: true,
			url:Com_Parameter.ContextPath + "/common/getDataList?s_bean=getBaseDataService",
			dataFilter: ajaxDataFilterBaseData
		},
		view:{
			showLine: false,
			dblClickExpand: false
		},
		data : {
			simpleData : {
				enable : true
			},
			key :{
				title : "fullName",
				isFun : "isFun",
				isData : "isData"
			}
		},
		callback: {
			onMouseDown: zTreeOnMouseDown
		}
	};
	
	function ajaxDataFilterBaseData(treeId, parentNode, responseData) {
	   if (responseData) {
	      for(var i =0; i < responseData.length; i++) {
	    	  if(responseData[i].isData)
	    	  	formulaGobalInfo.basedataInfo[responseData[i].id] = responseData[i].name;
	      }
	   }
	   return responseData;
	};
	//初始化服务树
	var setting_service = {
		async: {
			enable: true,
			url:Com_Parameter.ContextPath + "/common/getDataList?s_bean=getServiceInfoService",
			dataFilter: ajaxDataFilterService
		},
		view:{
			showLine: false,
			dblClickExpand: false
		},
		data : {
			simpleData : {
				enable : true
			},
			key :{
				title : "fullName",
				isFun : "isFun",
				isData : "isData"
			}
		},
		callback: {
			onMouseDown: zTreeOnMouseDown
		}
	};
	
	function ajaxDataFilterService(treeId, parentNode, responseData) {
	   if (responseData) {
	      for(var i =0; i < responseData.length; i++) {
	    	  if(responseData[i].isData)
	    	  	formulaGobalInfo.serviceInfo[responseData[i].id] = responseData[i].name;
	      }
	   }
	   return responseData;
	};
	
	//通用方法
	
	//鼠标单击树节点选择
	function zTreeOnMouseDown(event, treeId, treeNode) {	
		opFormula(treeNode.fullName,"");				
	};
	//初始化树
	$(document).ready(function(){
		$.fn.zTree.init($("#var_tree"), setting_vars);
		//$.fn.zTree.init($("#basedata_tree"), setting_basedata);
		$.fn.zTree.init($("#service_tree"), setting_service);
		$("#expression").val(window.dialogArguments.name);
	});
	
	</script>
</head>
<body>
	<div class="left">
		<div>
			<ul id="var_tree" class="ztree" style="width:230px; overflow:auto;"></ul>
		</div>
		<!-- 
		<div class="modal-body">
			<ul id="basedata_tree" class="ztree"></ul>
		</div>
		 -->
		<div>
			<ul id="service_tree" class="ztree"></ul>
		</div>
	</div>
	<div class="right">
	     <div class="right_1">
	     	  <br>
	     	  <br>
	          <textarea style="width: 95%;height: 85%" id="expression"></textarea>
	     </div>
	     <div class="right_2">
	          <table width="95%" class="tb_normal" border="0">
		        <tr align="center">
		          <td width="12%" class="tdNumber"><input type="button" class="bigButton" onclick="opFormula('1');" value="1"></td>
		          <td width="12%" class="tdNumber"><input type="button" class="bigButton" onclick="opFormula('2');" value="2"></td>
		          <td width="12%" class="tdNumber"><input type="button" class="bigButton" onclick="opFormula('3');" value="3"></td>
		          <td width="12%" class="tdOpr"><input type="button" class="bigButton" onclick="opFormula('/', ' ');" value="/"></td>
		          <td width="12%" class="tdOpr"><input type="button" class="bigButton" onclick="opFormula('(');" value="("></td>
		          <td width="12%" class="tdOpr"><input type="button" class="bigButton" onclick="opFormula(')', ' ');" value=")"></td>
		          <td width="14%" class="tdBl"><input type="button" class="bigButton" onclick="opFormula('&&', ' ');" value="&&" title=""></td>
		          <td width="14%" class="tdBl"><input type="button" class="bigButton" onclick="opFormula('||', ' ');" value="||" title=""></td>
		        </tr>
		        <tr align="center">
		          <td class="tdNumber"><input type="button" class="bigButton" onclick="opFormula('4');" value="4"></td>
		          <td class="tdNumber"><input type="button" class="bigButton" onclick="opFormula('5');" value="5"></td>
		          <td class="tdNumber"><input type="button" class="bigButton" onclick="opFormula('6');" value="6"></td>
		          <td class="tdOpr"><input type="button" class="bigButton" onclick="opFormula('*', ' ');" value="*"></td>
		          <td class="tdOpr"><input type="button" class="bigButton" onclick="opFormula('&lt;', ' ');" value="&lt;"></td>
		          <td class="tdOpr"><input type="button" class="bigButton" onclick="opFormula('>', ' ');" value="&gt;"></td>
		          <td class="tdBl"><input type="button" class="bigButton" onclick="opFormula('!', ' ');" value="!" title=""></td>
		          <td class="tdBl"><input type="button" class="bigButton" onclick="opFormula('!=', ' ');" value="!=" title=""></td>
		        </tr>
		        <tr align="center">
		          <td class="tdNumber"><input type="button" class="bigButton" onclick="opFormula('7');" value="7"></td>
		          <td class="tdNumber"><input type="button" class="bigButton" onclick="opFormula('8');" value="8"></td>
		          <td class="tdNumber"><input type="button" class="bigButton" onclick="opFormula('9');" value="9"></td>
		          <td class="tdOpr"><input type="button" class="bigButton" onclick="opFormula('-', ' ');" value="-"></td>
		          <td class="tdOpr"><input type="button" class="bigButton" onclick="opFormula('&lt;=', ' ');" value="&lt;="></td>
		          <td class="tdOpr"><input type="button" class="bigButton" onclick="opFormula('>=', ' ');" value="&gt;="></td>
		          <td class="tdBl"><input type="button" class="bigButton" onclick="opFormula(';', ' ');" value=";"></td>
		          <td class="tdBl"><input type="button" class="bigButton" onclick="opFormula(',', ' ');" value=","></td>
		        </tr>
		        <tr align="center">
		          <td class="tdNumber"><input type="button" class="bigButton" onclick="opFormula('0');" value="0"></td>
		          <td class="tdNumber"><input type="button" class="bigButton" onclick="opFormula('.');" value="."></td>
		          <td class="tdNumber"><input type="button" class="bigButton" onclick="opFormula('%', ' ');" value="%" title=""></td>
		          <td class="tdOpr"><input type="button" class="bigButton" onclick="opFormula('+', ' ');" value="+"></td>
		          <td class="tdOpr"><input type="button" class="bigButton" onclick="opFormula('=', ' ');" value="=" title=""></td>
		          <td class="tdOpr"><input type="button" class="bigButton" onclick="opFormula('==', ' ');" value="==" title=""></td>
		          <td class="tdBl" colspan="2"></td>
		        </tr>
		      </table>
	     </div>
	     <div class="right_3">
	          <ul>
	              <input type="button" class="bigButton" onclick="cleanInfo();" value="清除">
	              <input type="button" class="bigButton" onclick="submit();" value="确定">
	              <input type="button" class="bigButton" onclick="window.close();" value="关闭">
	          </ul>
	     </div>
	</div>
</body>
</html>